package com.asen.sys.handler;

import com.asen.sys.domain.DictItem;
import com.asen.commons.core.base.enums.DictTypeEnum;
import com.asen.commons.core.jdbc.handler.BaseTypeHandler;
import com.asen.sys.utils.DictUtils;

import java.sql.*;

/**
 * StringEnum
 *
 * @author Gary
 * @version 1.0
 * @date 2018-11-29
 */
public class DictTypeHandler extends BaseTypeHandler<DictItem> {

    private DictTypeEnum dictType;

    public DictTypeHandler(DictTypeEnum dictType) {
        this.dictType = dictType;
    }

    @Override
    public int getSqlType() {
        return Types.VARCHAR;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, DictItem parameter)
            throws SQLException {
        ps.setString(i, parameter.getValue());
    }

    @Override
    public DictItem getNullableResult(ResultSet rs, String columnName)
            throws Exception {
        String value = rs.getString(columnName);
        return DictUtils.getDictData(dictType, value);
    }

    @Override
    public DictItem getNullableResult(ResultSet rs, int columnIndex)
            throws Exception {
        String value = rs.getString(columnIndex);
        return DictUtils.getDictData(dictType, value);
    }

    @Override
    public DictItem getNullableResult(CallableStatement cs, int columnIndex)
            throws Exception {
        String value = cs.getString(columnIndex);
        return DictUtils.getDictData(dictType, value);
    }

    @Override
    public String toSqlValue(Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof String) {
            return "\'" + value + "\'";
        }

        if (value instanceof String[]) {
            return getSqlValue((String[]) value, true);
        }

        if (value instanceof DictItem) {
            return "\'" + ((DictItem) value).getValue() + "\'";
        }

        if (value instanceof DictItem[]) {
            DictItem[] actualValue = (DictItem[]) value;
            String[] sArr = new String[actualValue.length];
            int i = 0;
            for (DictItem item : actualValue) {
                sArr[i++] = item.getValue();
            }
            return getSqlValue(sArr, true);
        }

        return "\'" + value + "\'";
    }

    @Override
    public DictItem getValue(Object value) throws Exception {
        if (value == null) {
            return null;
        }

        if (DictItem.class.isAssignableFrom(value.getClass())) {
            return (DictItem) value;
        }

        if (String.class.isAssignableFrom(value.getClass())) {
            return DictUtils.getDictData(dictType, (String) value);
        }

        return DictUtils.getDictData(dictType, String.valueOf(value));
    }
}
